package apis

import (
	"encoding/json"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"gorm.io/gorm"
	"net/http"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/pkg/util"
	"tuowei.com/pkg/xlog"
)

type ApiMobileInvite struct {
	api.Api
}

func (e ApiMobileInvite) Invite(c *gin.Context) {
	req := dto.InviteLoginReq{}
	s := service.ApiStudent{}
	err := e.MakeContext(c).MakeOrm().
		Bind(&req, binding.JSON).
		MakeService(&s.Service).
		Errors
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	code, err := config.GetRedisClient().Get(util.MakeMessageCodeKey("invite", req.Phone)).Result()
	if err != nil {
		xlog.Error(err)
		e.Error(500, err, "请先获取验证码")
		return
	}

	if req.Code != code {
		err = errors.New("短信验证码错误")
		e.Error(500, err, err.Error())
		return
	}
	var claim *jwt.Token
	teacherRecommender := 0
	studentRecommender := 0

	claim, err = jwt.ParseWithClaims(req.Token, &InviteClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(config.JwtConfig.Secret), nil
	})
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	var object InviteClaims
	bys, _ := json.Marshal(claim.Claims)
	json.Unmarshal(bys, &object)
	if object.Id == 0 {
		e.Error(http.StatusInternalServerError, errors.New("邀请人信息错误"), "邀请人信息错误")
		return
	}
	if req.Type == "student" {
		studentRecommender = object.Id
	} else if req.Type == "teacher" {
		teacherRecommender = object.Id
	} else {
		e.Error(http.StatusInternalServerError, errors.New("非法类型"), "非法类型")
		return
	}

	var student models.SysStudent
	err = s.GetUserInfoByPhone(&student, req.Phone)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {

			studentData := &dto.SysStudentInsertReq{
				Phone:            req.Phone,
				Status:           1,
				Source:           req.Type,
				Recommender:      studentRecommender,
				TeachRecommender: teacherRecommender,
				Province:         0,
				City:             0,
			}
			_, insertErr := s.Insert(studentData)
			if insertErr != nil {
				xlog.Error(insertErr)
				e.Error(500, insertErr, insertErr.Error())
				return
			} else {
				e.OK(nil, "注册成功")
				return
			}
		} else {
			e.Error(http.StatusInternalServerError, err, err.Error())
			return
		}

	}
	e.OK(nil, "您已经注册过了,不能重新注册")
	//if student.Recommender != 0 {
	//	//可以发送信息给邀请人，提醒他邀请的人已经存在邀请人了
	//	err = errors.New("该学员已被邀请注册")
	//	e.Error(500, err, "该学员已被邀请注册")
	//	return
	//}
	//e.OK(nil, "成功")
	return

}
